package com.webserver.controller;

import com.webserver.core.ClientHandler;
import com.webserver.entity.User;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.URISyntaxException;

public class UserController {
    private static File rootDir;
    private static File staticDir;
    private static File userDir;
    static{

        try {
            rootDir=new File(
                    ClientHandler.class.getClassLoader()
                    .getResource(".").toURI()
            );
            staticDir =new File(rootDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        userDir=new File("users");
        if(!userDir.exists()){
            userDir.mkdirs();
        }

    }


    public void reg(HttpServletRequest request, HttpServletResponse response){

        String username =request.getParameter("username");
        String password =request.getParameter("password");
        String nickname =request.getParameter("nickname");
        String ageStr = request.getParameter("age");

        if(username==null||password==null||nickname==null||ageStr==null||
         !ageStr.matches("[0-9]+")){
            File file =new File(staticDir,"/myweb/reg_info_error.html");
            response.setContentFile(file);
            return;
        }
        int age=Integer.parseInt(ageStr);
        System.out.println(username+","+password+","+nickname+","+age);

        User user =new User(username,password,nickname,age);
        File userFile = new File(userDir,username+".obj");

        if(userFile.exists()){
            File file =new File(staticDir,"/myweb/have_user.html");
            response.setContentFile(file);
            return;
        }

        try {
            FileOutputStream fos = new FileOutputStream(userFile);
            ObjectOutputStream oos =new ObjectOutputStream(fos);

            oos.writeObject(user);

            File file=new File(staticDir,"/myweb/reg_success.html");
            response.setContentFile(file);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
